/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.listener;

import com.bifrost.entity.Order;
import com.bifrost.entity.OrderReturn;
import com.bifrost.entity.TransactionSendLog;
import com.bifrost.event.TransactionEvent;
import com.bifrost.repository.TransactionSendLogRepository;
import com.bifrost.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigDecimal;

/**
 * 交易创建事件监听器
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2018/5/18 17:27
 */
@Component
@Async
public class TransactionListener implements ApplicationListener<TransactionEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(TransactionListener.class);
    @Autowired
    TransactionSendLogRepository transactionSendLogRepository;
    @Autowired
    OrderService orderService;

    @Override
    public void onApplicationEvent(TransactionEvent transactionEvent) {
        try {
            Object source = transactionEvent.getSource();
            if (source instanceof Order) {
                Order order = (Order) source;
                Long id = order.getOrderId();
                TransactionSendLog existLog = transactionSendLogRepository.findFirstByOrderIdAndType(id, transactionEvent.getType());
                if (existLog == null) {
                    String storeCode = order.getMerchantStore().getExternalId();
                    TransactionSendLog log = new TransactionSendLog();
                    log.setType(transactionEvent.getType());
                    log.setOrderId(id);
                    log.setStroeCode(storeCode);
                    TransactionSendLog.Type type = transactionEvent.getType();
                    if (TransactionSendLog.Type.SALES.equals(type)) {
                        log.setTotal(order.getOrderTotal());
                        log.setTotalShippingFee(order.getTotalShippingFee());
                    }else{
                        log.setTotal(order.getOrderTotal().multiply(BigDecimal.valueOf(-1)));
                    }
                    log.setTransNumber(orderService.determineTransNumber(storeCode, type, id));
                    transactionSendLogRepository.save(log);
                }
            } else if (source instanceof OrderReturn) {
                OrderReturn order = (OrderReturn) source;
                Long id = order.getId();
                TransactionSendLog existLog = transactionSendLogRepository.findFirstByOrderIdAndType(id, transactionEvent.getType());
                if (existLog == null) {
                    String storeCode = order.getMerchantStore().getExternalId();
                    TransactionSendLog log = new TransactionSendLog();
                    log.setOrderId(id);
                    log.setTotal(order.getRefundTotal().multiply(BigDecimal.valueOf(-1)));
                    log.setType(transactionEvent.getType());
                    log.setStroeCode(storeCode);
                    log.setTransNumber(orderService.determineTransNumber(storeCode, transactionEvent.getType(), id));
                    transactionSendLogRepository.save(log);
                }

            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
